package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.vo.AppLogSearchVo;
import com.ruoyi.system.dto.AppLogSearchDTO;
import com.ruoyi.system.dto.MemberPackageDTO;
import com.ruoyi.system.service.IAppLoginLogService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/system/appLoginLog")
@Api(tags = "app登录日志")
public class AppLoginLogController {
    @Autowired
    private IAppLoginLogService loginLogService;

    /**
     * app登录日志列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppLogSearchVo searchVo)
    {
        startPage();
        List<AppLogSearchDTO> dto =  loginLogService.getList(searchVo);
        // 获取准确的总数
        int total = loginLogService.countList(searchVo);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(dto);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 大数据量CSV导出（流式，低内存占用）
     */
    @PostMapping("/export")
    public void export(@RequestBody AppLogSearchVo searchVo, HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("text/csv;charset=UTF-8");
        String fileName = "app_login_log_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".csv";
        String encoded = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + encoded);

        // 输出到客户端（写入UTF-8 BOM，Excel更好识别中文）
        PrintWriter writer = response.getWriter();
        writer.write('\uFEFF');

        // 写表头
        writer.println("id,userId,userName,mobile,ip,port,loginTime,clientId,platform,success");

        // 分批查询写出
        int pageNo = 1;
        final int pageSize = 2000; // 批大小，兼顾性能与内存
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (true) {
            List<AppLogSearchDTO> batch = loginLogService.getListByPage(searchVo, pageNo, pageSize);
            if (batch == null || batch.isEmpty()) {
                break;
            }
            for (AppLogSearchDTO dto : batch) {
                String loginTimeStr = dto.getLoginTime() != null ? sdf.format(dto.getLoginTime()) : "";
                // 逐行写入CSV，必要时做字段转义
                writer.println(String.join(",",
                        safe(dto.getId()),
                        safe(dto.getUserId()),
                        safe(dto.getUserName()),
                        safe(dto.getMobile()),
                        safe(dto.getIp()),
                        safe(dto.getPort()),
                        safe(loginTimeStr),
                        safe(dto.getClientId()),
                        safe(dto.getPlatform()),
                        safe(dto.getSuccess())
                ));
            }
            writer.flush();
            pageNo++;
        }
    }

    // 简单CSV安全转义（逗号/双引号/换行）
    private String safe(Object val) {
        String s = val == null ? "" : String.valueOf(val);
        if (s.contains(",") || s.contains("\n") || s.contains("\r") || s.contains("\"")) {
            s = '"' + s.replace("\"", "\"\"") + '"';
        }
        return s;
    }


}
